import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class DBManager {
  static bool isDebug = true;
  static String defaultDBName = 'mydb.db';
  static Database _database;

  static init({String dbName}) async {
    if (dbName != null && dbName.trim().length > 0) {
      defaultDBName = dbName;
    }
    var dataBasePath = await getDatabasesPath();
    String path = dataBasePath + "/" + defaultDBName;
    Database database = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      //初始化表
    });
    _database = database as Database;
    if (isDebug) {
      if (_database != null) {
        _log('打开数据库：成功');
      } else {
        _log('打开数据库：失败');
      }
    }
  }

  static Database getDb({String dbName}) {
    if (_database == null) {
      init(dbName: dbName);
    }
    return _database;
  }

  static closeDB() {
    if (_database != null) {
      _database.close();
      _log("关闭数据库！");
    }
  }

  static void _log(String msg) {
    if (isDebug) {
      print(
          "--------------------------------------------------------------------------------------------------------------");
      print("===>${msg}");
      print(
          "--------------------------------------------------------------------------------------------------------------");
    }
  }

  static _isExitTable(String tableName) async {
    String _selectTable =
        "select *  from sqlite_master where type='table' and name = '${tableName}'";
    var res = await getDb().rawQuery(_selectTable);
    if (res != null && res.length > 0) {
      return 1;
    }
    return -1;
  }

  static void delTable(String tableName) {
    if (tableName == null) {
      throw Exception('删除表失败：表名不能为空');
    }
    Database db = getDb();
    String url = 'DROP TABLE ${tableName}';
    db.execute(url);
    _log("执行语句：" + url);
  }

  static void clearTable(String tableName) {
    if (tableName == null) {
      throw Exception('清空表失败：表名不能为空');
    }
    Database db = getDb();
    String url = 'DELETE FROM  TABLE ${tableName}';
    db.execute(url);
    _log("执行语句：" + url);
  }

  static void createTable(String tableName, String createTableSql) async {
    if (createTableSql == null) {
      throw Exception('创建表失败：建表语句不能为null');
    }
    int flag = await _isExitTable(tableName);
    if (flag == 1) {
      throw Exception('创建表失败：该表已经存在了，不能重复建表');
    }
    Database db = getDb();
    String url = createTableSql;
    db.execute(url);
    _log("执行语句：" + url);
  }
}
